window.onload = function() {
    document.addEventListener('DOMContentLoaded', updateTopology());
    const legend2 = document.getElementById('legend2');
    const windowWidth = window.innerWidth;
    // 根据窗口大小动态设置 legend 位置
    legend2.style.left = `${windowWidth * 0.105}px`; // 左边距10%
}
window.onresize = function() {    
    const legend2 = document.getElementById('legend2');
    const windowWidth = window.innerWidth;
    // 根据窗口大小动态设置 legend 位置
    legend2.style.left = `${windowWidth * 0.105}px`; // 左边距10%
};

document.getElementById('dataForm').addEventListener('submit', function(event) {
    event.preventDefault();

    // 获取用户输入的地址
    const sheetname = document.getElementById('sheetname').value;

    // 发送POST请求到服务器
    fetch('/load_data', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ "sheetname": sheetname }),
    })
    .then(response => response.json())
    .then(data => {
        // 更新拓扑网络图
        updateTopology();
    })
    .catch(error => {
        console.error('Error:', error);
    });
});

function updateTopology() {
    // 清空之前的图形
    document.getElementById('topology').innerHTML = '';
    document.getElementById('legend').innerHTML = '';
    const width = document.getElementById('topology').clientWidth;
    const height = document.getElementById('topology').clientHeight;

    const svg = d3.select("#topology").append("svg")
        .attr("width", width)
        .attr("height", height)
        .call(d3.zoom().on("zoom", function (event) {
            svg.attr("transform", event.transform);
        }))
        .append("g");
    // 定义箭头标记
    svg.append('defs').append('marker')
        .attr('id', 'arrowhead')
        .attr('viewBox', '-0 -5 10 10')
        .attr('refX', 18)
        .attr('refY', 0)
        .attr('orient', 'auto')
        .attr('markerWidth', 10)
        .attr('markerHeight', 10)
        .attr('xoverflow', 'visible')
        .append('svg:path')
        .attr('d', 'M 0,-5 L 10,0 L 0,5 L 2,0 Z')
        .attr('fill', '#999')
        .style('stroke','none');

    const tooltip = d3.select("#tooltip"); // 选择 tooltip 元素

    // 加载网络拓扑数据
    d3.json('/topology').then(function (data) {
        // 动态生成图例
        console.log(data.links)
        const legend = document.getElementById('legend');
        group_item = {}
        Object.keys(data.group_info).forEach(groupId => {
            const group = data.group_info[groupId];
            group_item[groupId] = group.color;
            const legendItem = document.createElement('div');
            legendItem.className = 'legend-item';

            const legendColor = document.createElement('div');
            legendColor.className = 'legend-color';
            legendColor.style.backgroundColor = group.color;

            const legendText = document.createElement('span');
            legendText.textContent = group.name;

            legendItem.appendChild(legendColor);
            legendItem.appendChild(legendText);
            legend.appendChild(legendItem);
        });

        const simulation = d3.forceSimulation(data.nodes)
            .force("link", d3.forceLink(data.links).id(d => d.id).distance(50))
            .force("charge", d3.forceManyBody().strength(-2500))
            .force("center", d3.forceCenter(width / 2, height / 2))
            .force("x", d3.forceX().strength(0.1).x(d => width / 2))
            .force("y", d3.forceY().strength(0.01).y(d => height / 2));

        // 绘制连线
        const link = svg.append("g")
            .attr("class", "links")
            .selectAll("line")
            .data(data.links)
            .enter().append("line")
            .attr("stroke-width", d => Math.sqrt(d.value))
            .attr("stroke", "#999")
            .attr("marker-end", "url(#arrowhead)");  // 添加箭头

        // 绘制节点
        const node = svg.append("g")
            .attr("class", "nodes")
            .selectAll("circle")
            .data(data.nodes)
            .enter().append("circle")
            .attr("r", 20)
            .attr("fill", d => data.group_info[d.group].color)
            .on("mouseover", function (event, d) {
                tooltip.style("display", "block")
                    .html(`ip: ${d.ip}`)
                    .style("left", (event.pageX + 10) + "px")
                    .style("top", (event.pageY - 10) + "px");
            })
            .on("mouseout", function () {
                tooltip.style("display", "none");
            })
            .on("click", nodeClicked)  // 添加点击事件处理器
            .call(d3.drag()
                .on("start", dragstarted)
                .on("drag", dragged)
                .on("end", dragended));

        const labels = svg.append("g")
            .attr("class", "labels")
            .selectAll("text")
            .data(data.nodes)
            .enter().append("text")
            .attr("dy", 4) // 调整文本与节点的距离
            .attr("dx", 0)  // 调整文本与节点的水平偏移
            .attr("text-anchor", "middle")
            .attr("font-size", "14px")
            .attr("fill", "#fff")
            .text(d => d.id); // 使用节点的 id 作为标号
          

        // 更新仿真节点和连线的位置
        simulation.on("tick", () => {
            link
                .attr("x1", d => d.source.x)
                .attr("y1", d => d.source.y)
                .attr("x2", d => d.target.x)
                .attr("y2", d => d.target.y);

            node
                .attr("cx", d => d.x)
                .attr("cy", d => d.y);

            labels
                .attr("x", d => d.x)
                .attr("y", d => d.y);
        });

        // 节点点击事件处理函数
        function nodeClicked(event, d) {
            // 显示节点详细信息的面板
            const infoPanel = d3.select("#infoPanel");
            infoPanel.style("display", "block")
                     .html(`<h3>备注信息</h3>
                            <p>${d.card}</p>`);
        }
        const infoPanel = document.getElementById('infoPanel');
        // 点击 infoPanel 时隐藏面板
        infoPanel.addEventListener('click', function() {
            infoPanel.style.display = 'none';
        });

        // 拖动事件处理函数
        function dragstarted(event, d) {
            if (!event.active) simulation.alphaTarget(0.3).restart();
            d.fx = d.x;
            d.fy = d.y;
        }

        function dragged(event, d) {
            d.fx = event.x;
            d.fy = event.y;
        }

        function dragended(event, d) {
            if (!event.active) simulation.alphaTarget(0);
            d.fx = null;
            d.fy = null;
        }
        
         // 更新 legend2 内容
        const legend2 = document.getElementById('legend2');
        legend2.innerHTML = '';
        data.nodes.forEach(node => {
            const div_w = document.createElement('div');
            div_w.className = 'legend-item';

            const span = document.createElement('span');
            span.className = 'color-box';
            gid = `${node.group}`;
            span.style.backgroundColor = group_item[gid];

            div_w.appendChild(span);
            var text = document.createTextNode(`${node.id} - ${node.ip}`)
            div_w.appendChild(text);

            legend2.appendChild(div_w);
        });

    });
}
